<?php
	require("includes/database.php");

	
	$user = addslashes($_POST[username]);
	$pass = $_POST[password];
	
	$sql = "SELECT * FROM usuarios WHERE username='" . $user . "' AND password='" . md5($pass) . "'";
	$result = readSQL($sql);
	if(count($result) == 0)
	{
		$sql = "SELECT * FROM usuarios WHERE username='" . $user . "'";
		$result = readSQL($sql);
		if(count($result) == 0)
			header("Location: index.php?error=0");
		else
			header("Location: index.php?error=1&user=" . $user);
	}
	else
		{
			session_start();
			foreach($result as $value)
			{
				$_SESSION['username'] = $_POST[username];
				$_SESSION['idUsuario'] = $value['idUsuario'];
				$_SESSION['nombre'] = $value['nombre'];
				$_SESSION['apellido'] = $value['apellido'];
				$_SESSION['idSucursal'] = $value['idSucursal'];
				$arr = array();
				$sql2 = "SELECT * FROM usuariosxperfil u JOIN permisosxperfil p ON (u.idPerfil = p.idPerfil) WHERE u.idUsuario=" . $value['idUsuario'];
				$result2 = readSQL($sql2);
				if(count($result2) != 0)
				{
					foreach($result2 as $value2)
					{
						array_push($arr, $value2['idPermiso']);
					}
					$_SESSION['permisos'] = $arr;
					
					header("Location: main.php");
				}
				else
					header("Location: index.php?error=2");
			}
		}
?>